package cn.devhost;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.lingyangwl.framework.core.utils.IpUtils;
import cn.lingyangwl.framework.tool.core.CommandExecutor;
import cn.lingyangwl.framework.tool.core.StringUtils;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author shenguangyang
 */
@Slf4j
@Service
public class NetworkService {
    @Resource
    private ServerProperties properties;
    @Resource
    private JavaMailSender mailSender;
    @Resource
    private MailProperties mailProperties;

    private static final AtomicReference<String> preRowContent = new AtomicReference<>("");


    public void processResult(String item, StringBuilder rowContext, String findIpResult) throws Exception {
        findIpResult = StringUtils.defaultIfEmpty(findIpResult, "未发现或未启动");
        rowContext.append("</br>").append(item).append(" =====================>> </br>");
        if (!IpUtils.isIPv4Valid(findIpResult)) {
            rowContext.append("<span style=\"color: red;\">").append(findIpResult).append("</span></br>");
        } else {
            rowContext.append("<span style=\"color: greed;\">").append(findIpResult).append("</span></br>");
        }
    }

    public void sendEmail(List<NetworkInfo> networkInfos) {
        StringBuilder emailContent = new StringBuilder("\n");
        networkInfos.forEach(item -> {
            try {
                processResult(item.getInterfaceName(), emailContent, item.getIp());
            } catch (Exception e) {
                log.error("error: ", e);
                emailContent.append("<span style=\"color: greed;\">").append(e.getMessage()).append("</span></br>");
            }
        });

        String emailContentStr = emailContent.toString();
        if (!emailContentStr.equals(preRowContent.get())) {
            // 发送邮件通知
            sendMail(emailContentStr);
        }
        preRowContent.set(emailContentStr);
    }

    public void sendMail(String content) {
        log.info("发送邮件通知");
        MimeMessage message = mailSender.createMimeMessage();
        try {
            if (StringUtils.isEmpty(properties.getMailReceiveUser())) {
                log.error("邮件接收者尚未配置");
                return;
            }
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(mailProperties.getUsername());
            helper.setTo(properties.getMailReceiveUser());
            helper.setSubject("网络变动提醒");
            helper.setText(content, true);
            mailSender.send(message);
        } catch (Exception e) {
            log.error("send mail to [{}] fail, error: {}", properties.getMailReceiveUser(), e.getMessage());
        }
    }
}
